package symbolexp;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.logging.Logger;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class SymbolExperiment extends JFrame {
	final static Logger logger = Logger.getLogger(SymbolExperiment.class
			.getName());

	private static String symbolFile = "resources/syms.txt";
	private static String pairFile = "resources/pairs.txt";
	ArrayList<Pair> pairsList;
	HashMap<String, Symbol> symsBag;

	public SymbolExperiment(String string) {
		super(string);
		loadData();

	}

	private void loadData() {
		this.symsBag = new HashMap<String, Symbol>();
		this.pairsList = new ArrayList<Pair>();
		readSymbolFile();
		readPairFile();

	}

	private void readSymbolFile() {
		InputStream shpStream = this.getClass().getResourceAsStream(symbolFile);
		Scanner scan = new Scanner(shpStream);

		while (scan.hasNext()) {
			String line = scan.nextLine();
			Scanner lineScan = new Scanner(line);
			lineScan.useDelimiter(",");

			Symbol sym = new Symbol();
			sym.name = lineScan.next();
			logger.info("name = " + sym.name);
			String condName = lineScan.next();
			logger.info("condName = " + condName);
			sym.cond = Symbol.findCondition(condName);
			logger.info("cond = " + sym.cond);
			sym.im = readImage(sym.name);

			symsBag.put(sym.name, sym);
		}
	}

	private void readPairFile() {
		InputStream shpStream = this.getClass().getResourceAsStream(pairFile);
		Scanner scan = new Scanner(shpStream);

		while (scan.hasNext()) {
			String line = scan.nextLine();
			Scanner lineScan = new Scanner(line);
			lineScan.useDelimiter(",");

			Pair pr = new Pair();
			pr.firstSymbol = symsBag.get(lineScan.next());
			pr.secondSymbol = symsBag.get(lineScan.next());
			pr.question = lineScan.next();
			String value = lineScan.next();
			if (value.equalsIgnoreCase("yes")) {
				pr.truthValue = true;
			} else if (value.equalsIgnoreCase("no")) {
				pr.truthValue = false;
			} else {
				logger.severe("unknown truth value " + value);
			}
			pairsList.add(pr);

		}

	}

	private BufferedImage readImage(String name) {
		String fileName = "resources/" + name + ".png";
		InputStream imStream = this.getClass().getResourceAsStream(fileName);
		try {
			return ImageIO.read(imStream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.severe("failed to read image " + name);
		return null;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SymbolExperiment symExp = new SymbolExperiment("Symbol Experiment");
		symExp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		symExp.pack();
		symExp.setVisible(true);

	}

}
